<template>
  <div class="p-d">
    <div class="sql-copy admin-page b-f p-d m-b">
      <div class="title-top">
        <h1>数据备份</h1>
      </div>
      <div>
        <div class="btnStyle m-t m-b">
          <el-button type="primary" size="mini" @click="backFun">备份</el-button>
          <el-upload ref="uploadRef" class="upload-demo m-l" action="#" :limit="1" :on-change="handleChange" :auto-upload="false"
            :show-file-list="false" :on-exceed="handleExceed">
            <template #trigger>
              <el-button type="primary" size="mini">恢复</el-button>
            </template>
          </el-upload>
        </div>
        <el-row>
          <el-table class="m-b" :data="tableData" :height="`50vh`">
            <el-table-column label="序号" align="center" width="100">
              <template slot-scope="scope">
                <span>{{
                scope.$index + (pagination.page - 1) * pagination.size + 1
              }}</span>
              </template></el-table-column>
            <el-table-column label="备份时间" align="center" prop="backupTime" />
            <el-table-column label="备份方式" align="center" prop="backupMode" />
            <el-table-column label="备份类型" align="center" prop="backupType" />
            <el-table-column label="状态" align="center" prop="backupStatus" />
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false" @click="importFun(scope.row)">导出</el-link>
                <el-link class="m-l" type="danger" :underline="false" @click="del(scope.row)">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="end">
            <el-pagination v-if="pagination.total > 0" background layout="prev, pager, next" :total="pagination.total"
              :current-page.sync="pagination.page" :page-size="pagination.size" @current-change="initData" />
          </el-row>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getList,
  deleteList,
  updateBackup,
  handBackup,
  recoverData,
  exportBackup,
  exportBackupById,
  importBackupFile
} from '@/api/backup'
export default {
  name: 'BasisSqlCopy',
  data() {
    return {
      form: {
        backupInterval: '',
        backupWay: '',
        backupFlag: 0
      },
      pagination: {
        total: 0,
        size: 10,
        page: 1
      },
      tableData: [],
      rules: {
        backupInterval: [
          {
            required: true,
            message: '请选择数据备份间隔时间',
            trigger: 'change'
          }
        ],
        radio: [
          { required: true, message: '请选择备份方式', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    backFun() {
      exportBackup().then(() => {
        this.initData()
      })
    },
    handleChange(file) {
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      importBackupFile(formData).then(() => {
        this.initData()
      })
    },
    // 多次上传覆盖
    handleExceed(file) {
      this.$refs.uploadRef.clearFiles()
      this.handleChange(file[0])
    },
    // 开启自动备份
    handleCopy() {
      this.$refs.formDataRef.validate((valid) => {
        if (valid) {
          this.$confirm(
            '确认开启自动备份功能？系统将在24点开启第一次数据备份！',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            const params = {
              backupInterval: this.form.backupInterval,
              backupWay: this.form.backupWay
            }
            updateBackup(params)
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success(res.message)
                  this.initData()
                } else {
                  this.$message.error(res.message)
                  this.initData()
                }
              })
              .finally(() => {
                this.initData()
              })
          })
        } else {
          return false
        }
      })
    },

    // 关闭自动备份
    cancelCopy() {
      this.$confirm('是否取消自动备份？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          backupInterval: '',
          backupWay: ''
        }
        updateBackup(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message);
              (this.form = {
                backupInterval: '',
                backupWay: '',
                backupFlag: 0
              }),
                this.initData()
            } else {
              this.$message.error(res.message)
              this.initData()
            }
          })
          .finally(() => {
            this.initData()
          })
      })
    },
    // 立即手动备份
    handleBackup() {
      this.$confirm('是否手动备份？确认后将立即执行一次数据备份！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        handBackup()
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.initData()
            } else {
              this.$message.error(res.message)
              this.initData()
            }
          })
          .finally(() => {
            this.initData()
          })
      })
    },
    // 初始化表格数据
    initData() {
      const params = {
        currentPage: this.pagination.page,
        pageSize: this.pagination.size
      }
      getList(params).then((res) => {
        this.form = res.data.backupSetting ? res.data.backupSetting : this.form
        this.tableData = res.data.backupPage
        this.pagination.total = res.data.total
      })
    },
    // 恢复
    recover(item) {
      this.$confirm('是否恢复备份的数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        recoverData({ id: item.id })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.initData()
            } else {
              this.$message.error(res.message)
              this.initData()
            }
          })
          .finally(() => {
            this.$alert(
              '数据恢复时间较长，请耐心等待！请刷新系统后使用！',
              '警告',
              {
                confirmButtonText: '确定'
              }
            )
            this.initData()
          })
      })
    },
    importFun(item) {
      exportBackupById({ id: Number(item.id) }).then((res) => {
        if (!res.data) {
          this.$message({
            type: "warning",
            message: "无法下载",
          });
          return;
        }
        window.location.href = res.data || '';
      })
    },
    // 删除
    del(item) {
      this.$confirm('是否删除备份记录？删除后备份的数据将无法恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteList({ id: item.id })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.initData()
            } else {
              this.$message.error(res.message)
              this.initData()
            }
          })
          .finally(() => {
            this.initData()
          })
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .sql-copy {
    .heightStyle {
      height: 85vh;
    }
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
  .backStyle {
    position: relative;
    top: 5px;
  }
  :deep(.el-table .cell) {
    font-size: 16px;
  }
  :deep(.el-table th > .cell) {
    font-size: 18px;
  }
  .upload-demo {
    display: inline-block;
  }
</style>
